package com.baitiaojun.system.admin.controller.auth;

import com.baitiaojun.common.domain.model.result.CommonResult;
import com.baitiaojun.common.domain.model.result.Message;
import com.baitiaojun.common.utils.desensitize.RSAUtil;
import com.baitiaojun.ratelimit.core.annotation.RateLimit;
import com.baitiaojun.security.core.service.AuthenticationService;
import com.baitiaojun.system.admin.controller.auth.req.AuthLoginReq;
import com.baitiaojun.system.admin.service.auth.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Api("认证控制器")
@RestController
@RequestMapping("/admin/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private AuthenticationService authenticationService;

    @ApiOperation("获取公共密钥")
    @RateLimit(key = "publickey", count = 3, time = 1, RATE_LIMIT_TYPE = RateLimit.RateLimitType.IP)
    @GetMapping("/publicKey")
    public CommonResult getRSAPublicKey() {
        return CommonResult.ok(RSAUtil.getPublicKeyStr());
    }

    @RateLimit(key = "login", count = 30, time = 3, RATE_LIMIT_TYPE = RateLimit.RateLimitType.IP)
    @ApiOperation("登陆接口")
    @PostMapping("/login")
    public CommonResult login(@RequestBody @Validated AuthLoginReq authLoginDTO, HttpServletRequest request) {
        log.info("===================开始登陆===================");
        String tenant = request.getHeader("tenant");
        String token = authService.login(authLoginDTO, tenant);
        log.info("===================登陆成功===================");
        return CommonResult.ok().put("token", token);
    }

    @RateLimit(key = "logout", count = 50, time = 3, RATE_LIMIT_TYPE = RateLimit.RateLimitType.IP)
    @ApiOperation("登出接口")
    @PostMapping("/logout")
    public CommonResult logout() {
        log.info("===================开始登出===================");
        authService.logout();
        log.info("===================登出成功===================");
        return CommonResult.ok();
    }
}
